package com.haoze.nurse.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.dto.AgeDTO;
import com.haoze.common.enumeration.ConstantEnum;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.DateUtil;
import com.haoze.common.utils.HttpClientUtil;
import com.haoze.nurse.aop.NurseLogAop;
import com.haoze.nurse.component.PatientComponent;
import com.haoze.nurse.dao.NursePatientMapper;
import com.haoze.nurse.dao.TransfusionMapper;
import com.haoze.nurse.enumeration.StateEnum;
import com.haoze.nurse.service.NursePatientService;
import com.haoze.nurse.service.PatientService;
import com.haoze.nurse.dao.PatientMapper;
import com.haoze.nurse.dao.TaskExecuteMapper;
import com.haoze.nurse.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class PatientServiceImpl implements PatientService {

    @Resource
    PatientMapper patientMapper;

    @Resource
    TransfusionMapper transfusionMapper;

    @Resource
    TaskExecuteMapper taskExecuteMapper;

    @Resource
    NursePatientService nursePatientService;

    @Resource
    PatientComponent patientComponent;

    @Autowired
    NursePatientMapper nursePatientMapper;

    @Value("${his.url.cost}")
    private String cost;

    @Value("${his.url.operationUrl}")
    private String operationUrl;

    @Value("${his.url.environmentFlag}")
    private String environmentFlag;

    private static final Logger log = LoggerFactory.getLogger(NurseLogAop.class);

    @Value("${spring.profiles.active}")
    private String activeType;

    @Override
    public Result getPatientInfoCards(Integer page, Integer pageSize, String wardId, String search) {
        PageHelper.startPage(page, pageSize);
        List<Map<String, Object>> patientList = patientMapper.queryPatients(wardId, search);

        patientList.parallelStream().forEach(patient -> {
            String deptId = patient.get("deptId").toString();
            getPatientAge(patient);//处理病人年龄
            if (deptId.equals("95037CF5C9465245E053ED5B14ACFD88") || deptId.equals("95037CF5C9475245E053ED5B14ACFD88")) {
                patient.put("infoType", "anaesthesia");//麻醉
            } else if (deptId.equals("F0F3BC5868CE47F583CB08EC6E46B1D6") || deptId.equals("5D04523554944A30A5FB81F57E985763")) {
                patient.put("infoType", "operation");//手术
            } else {
                patient.put("infoType", "orther");//其他
            }

            //费别 注释的是正式参数与返回
            String url = cost;
            Map<String, Object> param = new HashMap<>();

            param.put("as_patientId", patient.get("inpatNum").toString().replace("-1", ""));
            param.put("operationID", "10001");
            param.put("al_visitId", "1");
            param.put("al_doctor_type", "");

            CompletableFuture<String> ordedCustomerFuture = CompletableFuture.supplyAsync(() ->
                    HttpClientUtil.sendPost(url, param)).thenApply(x -> x.toString());
            try {
                JSONObject jsonObject = JSON.parseObject(ordedCustomerFuture.get());
                if (jsonObject.getString("data") != null) {
                    Map cost = JSONArray.parseArray(jsonObject.getString("data"), Map.class).get(0);
                    if (cost.get("CHARGE_TYPE").toString().contains("自费")) {
                        patient.put("payOff", "自费");
                    } else {
                        patient.put("payOff", cost.get("CHARGE_TYPE").toString());
                    }
                }
            } catch (Exception e) {
                log.error("查询费用明细失败", e);
            }
            patient.putAll(getIdentification(patient.get("inpatNum").toString()));//护理登记  病重 药物过敏 危险标识
        });
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(patientList);
        return ResultGenerator.genOkResult(pageInfo);
    }

    public static String comparingByBedNo(Map<String, String> map) {
        return map.get("ROOM_NO");
    }

    @Override
    public Result getPatientInfo(String qrCode) {
        String inpatNum = taskExecuteMapper.queryInpatNumByQrcode(qrCode);
        if (StringUtils.isBlank(inpatNum)) {
            inpatNum = transfusionMapper.queryInfoByBarCode(qrCode);
        }
        //根据入院号获取当前病人信息（姓名，入院号，年龄，床号，性别）
        Map<String, String> patientMap = this.getPatientInfoWithComputeAge(inpatNum);
        return ResultGenerator.genOkResult(patientMap);
    }

    @Override
    public Result conditionInfo(String inpatNum, String wardId) {
        //根据入院号获取当前病人信息（姓名，入院号，年龄，床号，性别）等病人基础信息
        Map<String, String> patientMap = this.getPatientInfoWithComputeAge(inpatNum);
        if (patientMap == null)
            return ResultGenerator.genFailedResult("无此住院病人信息");

        List<String> nursingGradeList = Arrays.asList(StateEnum.IJHL.getValue(), StateEnum.IJHLEK.getValue(), StateEnum.IIJHL.getValue(),
                StateEnum.IIIJHLEK.getValue(), StateEnum.IIIJHL.getValue(), StateEnum.IIIJHLEK.getValue(),
                StateEnum.YJHL.getValue(), StateEnum.EJHL.getValue(), StateEnum.SJHL.getValue(),
                StateEnum.TJHL.getValue(), StateEnum.TJHLEK.getValue(), StateEnum.JHBFYJHL.getValue(),
                StateEnum.JHBFEJHL.getValue(), StateEnum.JHBFTJHL.getValue());
        String dateTime = DateUtil.dateToString(new Date(),"yyyy-MM-dd");
        List<Map<String, String>> nursingGradeLists = nursePatientMapper.queryNursingGradeByInpatNum(Arrays.asList(inpatNum), dateTime,nursingGradeList);
        AtomicReference<String> nursingGrade= new AtomicReference<>("无");
        nursingGradeLists.parallelStream().forEach(filterNursingGrade->{
            if(StateEnum.TJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.TJHLEK.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.JHBFTJHL.getValue().equals(filterNursingGrade.get("varCode"))){
                nursingGrade.set(StateEnum.TJHL.getText());
            }else if(StateEnum.IJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.IJHLEK.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.YJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.JHBFYJHL.getValue().equals(filterNursingGrade.get("varCode"))){
                nursingGrade.set(StateEnum.YJHL.getText());
            }else if(StateEnum.IIJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.IIJHLEK.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.EJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.JHBFEJHL.getValue().equals(filterNursingGrade.get("varCode"))){
                nursingGrade.set(StateEnum.EJHL.getText());
            }else if(StateEnum.IIIJHL.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.IIIJHLEK.getValue().equals(filterNursingGrade.get("varCode")) || StateEnum.SJHL.getValue().equals(filterNursingGrade.get("varCode"))){
                nursingGrade.set(StateEnum.SJHL.getText());
            }
        });
        patientMap.put("religiousBelief", patientMap.get("religion"));//宗教信仰
        patientMap.put("drugBacterialInfection", "无");//多重耐药菌感染信息
        patientMap.put("allergicDrugs", "无");//过敏药物信息
        patientMap.put("highRisk", "无");//病人高危信息
        patientMap.put("familyHistory", "无");//家族史
        patientMap.put("operationHistory", "无");//手术史
        patientMap.put("disease", "无");//曾患疾病
        patientMap.put("smokingHistory", "无");//吸烟史
        patientMap.put("drinkingHistory", "无");//饮酒史
        patientMap.put("eatingHabits", "无");//饮食习惯
        patientMap.put("supportSystem", "无");//支持系统
        patientMap.put("hospitalConcerns", "无");//住院顾虑
        patientMap.put("degreeEducation", patientMap.get("education"));//文化程度
        patientMap.put("height", "无");//身高
        patientMap.put("weight", "无");//体重
        //费别 注释的是正式参数与返回
        String url = cost;
        Map<String, Object> param = new HashMap<>();
        param.put("as_patientId", inpatNum.replace("-1", ""));
        param.put("operationID", "10001");
        param.put("al_visitId", "1");
        param.put("al_doctor_type", "");
        CompletableFuture<String> ordedCustomerFuture = CompletableFuture.supplyAsync(() ->
                HttpClientUtil.sendPost(url, param)).thenApply(x -> x.toString());
        try {
            JSONObject jsonObject = JSON.parseObject(ordedCustomerFuture.get());
            if (jsonObject.getString("data") != null) {
                Map cost = JSONArray.parseArray(jsonObject.getString("data"), Map.class).get(0);

                if (cost.get("YE_JE") != null) {//余额
                    BigDecimal state = new BigDecimal(cost.get("YE_JE").toString());
                    patientMap.put("payOffState", state.toString());
                } else {
                    patientMap.put("payOffState", "0");
                }
                if (cost.get("YJJ_AMT") != null && StringUtils.isNotBlank(cost.get("YJJ_AMT").toString())) {//预交金总额
                    BigDecimal state = new BigDecimal(cost.get("YJJ_AMT").toString());
                    patientMap.put("yjjAmt", state.toString());
                } else {
                    patientMap.put("yjjAmt", "0");
                }
                if (cost.get("ZL_JE") != null && StringUtils.isNotBlank(cost.get("ZL_JE").toString())) {//自理现金
                    BigDecimal state = new BigDecimal(cost.get("ZL_JE").toString());
                    patientMap.put("zlJe", state.toString());
                } else {
                    patientMap.put("zlJe", "0");
                }
                if (cost.get("TOTAL_COST") != null && StringUtils.isNotBlank(cost.get("TOTAL_COST").toString())) {//未结总费用
                    BigDecimal state = new BigDecimal(cost.get("TOTAL_COST").toString());
                    patientMap.put("totalCost", state.toString());
                } else {
                    patientMap.put("totalCost", "0");
                }

                if (cost.get("CHARGE_TYPE").toString().contains("自费")) {
                    patientMap.put("payOff", "自费");
                } else {
                    patientMap.put("payOff", cost.get("CHARGE_TYPE").toString());
                }
            }
        } catch (Exception e) {
            log.error("查询费用明细失败", e);
        }

        // 获取血型
        patientComponent.componentBlood(patientMap);
//        String bloodType = patientMapper.getBloodType(inpatNum);
        patientMap.put("bloodType", "");

        //入院诊断取最新值
//		String admissionDiagnosis = "";//入院诊断
//		List<Map<String,String>> admission = transfusionMapper.queryAdmissionDiagnosis(inpatNum);
//		for(int i=0;i<admission.size();i++){
//			Map<String,String> item = admission.get(i);
//			admissionDiagnosis += i+1 +"."+item.get("DATA_VALUE")+";\n";
//		}
//		if(StringUtils.isNotBlank(admissionDiagnosis)) {
//            patientMap.put("admissionDiagnosis", admissionDiagnosis);
//        }else{
//            patientMap.put("admissionDiagnosis", "无");
//        }

        //获取手术信息
        if ("95037CF5C9465245E053ED5B14ACFD88".equals(wardId) || "95037CF5C9475245E053ED5B14ACFD88".equals(wardId)) {
            //调用his
            Map<String, String> params = new HashMap<String, String>();
            params.put("as_patient_id", inpatNum.split("-")[0]);
            params.put("as_operating_room", "");
            params.put("operationID", ConstantEnum.HIS_PATIENT_CENTER_10003.getKey());
            System.out.println(JSON.toJSONString(params));
            JSONObject jsonObject = HttpClientUtil.sendPost(operationUrl, params);
            if (jsonObject.isEmpty()) {
                //return ResultGenerator.genFailedResult("获取手术数据失败");
            }
            if (null != jsonObject) {
                Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                if (resInt < 0) {
                    //return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                }
            }
            if (jsonObject.getString("data") != null) {
                List<Map<String, String>> list = JSON.parseObject(jsonObject.getString("data"), new TypeReference<List<Map<String, String>>>() {
                });
                if (!CollectionUtils.isEmpty(list)) {
                    patientMap.putAll(list.get(0));
                    if (StringUtils.isNotBlank(list.get(0).get("IN_PACU_DATE_TIME"))) {
                        patientMap.put("IN_DATE_TIME", list.get(0).get("IN_PACU_DATE_TIME").substring(0, 16));
                    }
                }
            }
            //城中                                                             //阳湖
        } else if ("F0F3BC5868CE47F583CB08EC6E46B1D6".equals(wardId) || "5D04523554944A30A5FB81F57E985763".equals(wardId)) {
            //调用his
            Map<String, String> params = new HashMap<String, String>();
            params.put("as_patient_id", inpatNum.split("-")[0]);
            params.put("as_operating_room", "");
            params.put("operationID", ConstantEnum.HIS_PATIENT_CENTER_10002.getKey());
            System.out.println(JSON.toJSONString(params));
            JSONObject jsonObject = HttpClientUtil.sendPost(operationUrl, params);
            if (jsonObject.isEmpty()) {
                //return ResultGenerator.genFailedResult("获取手术数据失败");
            }
            if (null != jsonObject) {
                Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                if (resInt < 0) {
                    //return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                }
            }
            if (jsonObject.getString("data") != null) {
                List<Map<String, String>> list = JSON.parseObject(jsonObject.getString("data"), new TypeReference<List<Map<String, String>>>() {
                });
                if (!CollectionUtils.isEmpty(list)) {
                    patientMap.putAll(list.get(0));
                    if (StringUtils.isNotBlank(list.get(0).get("IN_DATE_TIME"))) {
                        patientMap.put("IN_DATE_TIME", list.get(0).get("IN_DATE_TIME").substring(0, 16));
                    }
                }
            }
        }

        String bedno = patientMap.get("wardDept");
        // 处理床号,当出院病人床号为0时显示最近一次护理记录单中记录的床号
        if ("0".equals(bedno)) {
            // 获取记录时间最近的护理记录，从中获取床号
            bedno = patientMapper.getLatestBedNo(inpatNum);
            if (StringUtils.isNotEmpty(bedno)) {
                patientMap.put("wardDept", bedno);
            }
        }

        Map result = new HashMap();
        result.putAll(patientMap);
        result.putAll(getIdentification(inpatNum));//护理登记  病重 药物过敏 危险标识
        result.put("currentDiagnosis", nursePatientService.getDiagName(inpatNum));
        result.put("nursingGrade",nursingGrade.get());//体重
        return ResultGenerator.genOkResult(result);
    }

    public Map<String, Object> getIdentification(String inpatNum) {
        Map<String, Object> patientMap = new HashMap<>();
        Map<String, String> conditions = new HashMap<>();
        List<Map<String, String>> condList = patientMapper.queryConditionInfo(inpatNum);//护理登记  病重 药物过敏 危险标识
        for (Map<String, String> cond : condList) {
            if (cond != null) {
                if ("drugBacterialInfection".equals(cond.get("type"))) {
                    conditions.put("drugBacterialInfection", cond.get("data"));
                }
                /*else if ("nursingGrade".equals(cond.get("type"))) {
                    conditions.put("nursingGrade", cond.get("data"));
                }*/
                else if ("responsibleNursePerson".equals(cond.get("type"))) {
                    conditions.put("responsibleNursePerson", cond.get("data"));
                } else if ("disdaseState".equals(cond.get("type"))) {
                    conditions.put("disdaseState", cond.get("data"));
                } else if ("allergicDrugs".equals(cond.get("type"))) {
                    conditions.put("allergicDrugs", toRepeatList(cond.get("data")));
                } else if ("eatingHabits".equals(cond.get("type"))) {
                    conditions.put("eatingHabits", toRepeatList(cond.get("data")));
                }
            }
        }
        List<Map<String, String>> highRiskListOral = patientMapper.queryHighRisk(inpatNum);//高危信息
//		List<Map<String,String>> highRiskListOral = new CopyOnWriteArrayList<>();
//		highRiskLisData.parallelStream().forEach(x ->{
//			if("0b7448e0ced74d1c9ac9c97b0fc7a6ee".equals(x.get("ELEMENT_ID"))){
//				highRiskLisData.parallelStream().forEach(x2 ->{
//					if(x.get("FILE_DATA_ID").equals(x2.get("FILE_DATA_ID")) && x.get("PARENT_ID").equals(x2.get("PARENT_ID")) && "8ceb62574f344a7cb6aae91badba641f".equals(x2.get("ELEMENT_ID"))){
//						Map<String,String> item = new HashMap<>();
//						item.put("fileDate",x.get("fileDate"));
//						item.put("fileDateModify",x.get("gmtModify"));
//						item.put("highRisk",x2.get("highRisk"));
//						if(x.get("DATA_VALUE") ==null){
//							item.put("tplName","");
//						}else{
//							item.put("tplName",x.get("DATA_VALUE"));
//						}
//						highRiskListOral.add(item);
//					}
//				});
//			}
//		});
        Map<String, List<Map<String, String>>> bookMap = null;
        List<Map<String, String>> highRiskList = new ArrayList<>();
        if (highRiskListOral != null && highRiskListOral.size() > 0) {
            bookMap = highRiskListOral.stream().collect(Collectors.groupingBy(b -> b.get("tplName")));
            for (String key : bookMap.keySet()) {
                List<Map<String, String>> keyItem = bookMap.get(key);
                keyItem.sort((a, b) -> (int) (DateUtil.stringToDate(b.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000) - (int) (DateUtil.stringToDate(a.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000));
                if (keyItem != null && keyItem.size() > 0) {
                    highRiskList.add(keyItem.get(0));
                }
            }
        }

        if (conditions == null) {
            conditions = new HashMap<>();
        }

        List<Map<String, String>> riskList = new CopyOnWriteArrayList();
        highRiskList.parallelStream().forEach(item -> {
            if (StringUtils.isNotBlank(item.get("highRisk")) && StringUtils.isNotBlank(item.get("tplName"))) {
                Map<String, String> riskMap = new HashMap<>();
                if (item.get("highRisk") != null) {//危险程度
                    Integer score = Integer.parseInt(item.get("highRisk").toString());
                    if (score < 25) {
                        riskMap.put("highRisk", "低危");
                    } else if (score >= 25 && score <= 45) {
                        riskMap.put("highRisk", "中危");
                    } else if (score > 45) {
                        riskMap.put("highRisk", "高危");
                    }
                } else {
                    riskMap.put("highRisk", "无");
                }

                riskMap.put("fileDate", item.get("fileDate"));
                riskMap.put("highRiskData", item.get("highRisk"));
                riskMap.put("fileDateModify", item.get("fileDateModify"));
                riskMap.put("tplName", item.get("tplName"));
                String tplName = item.get("tplName");
                Integer score = Integer.parseInt(item.get("highRisk"));
                if (item.get("highRisk") != null) {//危险程度
                    if ("Morse跌倒评分".equals(tplName)) {//跌倒
                        if (score >= 45) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 25 && score <= 44) {
                            riskMap.put("highRisk", "中危");
                        } else if (score < 25) {
                            riskMap.put("highRisk", "高危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("儿童跌倒/坠床评分".equals(tplName)) {//跌倒
                        if (score >= 12) {
                            riskMap.put("highRisk", "高危");
                        } else if (score < 12) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Braden评分".equals(tplName)) {//braden
                        if (score <= 9) {
                            riskMap.put("highRisk", "高危");//极高危
                        } else if (score >= 10 && score <= 12) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 13 && score <= 14) {
                            riskMap.put("highRisk", "中危");
                        } else if (score >= 15 && score <= 18) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Braden-Q评分".equals(tplName) && (score <= 10 || (score >= 11 && score <= 16))) {
                        if (score <= 10) {
                            riskMap.put("highRisk", "高危");//极高危
                        } else if (score >= 11 && score <= 16) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 17 && score <= 21) {
                            riskMap.put("highRisk", "中危");
                        } else if (score >= 22) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Barthel评分".equals(tplName) && score <= 40) {
                        if (score <= 40) {
                            riskMap.put("highRisk", "高危");//重度依赖
                        } else if (score >= 41 && score <= 60) {
                            riskMap.put("highRisk", "中危");//中度依赖
                        } else if (score >= 61 && score <= 99) {
                            riskMap.put("highRisk", "低危");//轻度依赖
                        } else if (score == 100) {
                            riskMap.put("highRisk", "");//无需依赖
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("营养风险筛查NRS2002评分".equals(tplName) && score >= 3) {
                        if (score >= 3) {
                            riskMap.put("highRisk", "高危");//重度
                        } else if (score == 2) {
                            riskMap.put("highRisk", "中危");//中度
                        } else if (score == 1) {
                            riskMap.put("highRisk", "低危");//轻度
                        } else if (score == 0) {
                            riskMap.put("highRisk", "");//正常
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("导管滑脱危险因素评分".equals(tplName) && score > 12) {
                        if (score > 12) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 8 && score <= 12) {
                            riskMap.put("highRisk", "中危");
                        } else if (score < 8) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    } else if ("Caprini评分".equals(tplName) && (score >= 5 || (score >= 3 && score <= 4))) {
                        if (score >= 5) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 3 && score <= 4) {
                            riskMap.put("highRisk", "中危");
                        } else if (score >= 1 && score <= 2) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    }else if ("Padua评分".equals(tplName) && (score >= 4 || (score >= 0 && score <= 3))) {
                        if (score >= 4) {
                            riskMap.put("highRisk", "高危");
                        } else if (score >= 0 && score <= 3) {
                            riskMap.put("highRisk", "低危");
                        } else {
                            riskMap.put("highRisk", "");
                        }
                    }
                } else {
                    riskMap.put("highRisk", "");
                }
                if ("Morse跌倒评分".equals(tplName) && score >= 45) {//跌倒
                    riskMap.put("highRiskName", "跌");
                } else if ("儿童跌倒/坠床评分".equals(tplName) && score >= 12) {//跌倒
                    riskMap.put("highRiskName", "跌");
                } else if ("Braden评分".equals(tplName) && (score <= 9 || (score >= 10 && score <= 12) || (score >= 13 && score <= 14))) {//braden
                    riskMap.put("highRiskName", "压");
                } else if ("Braden-Q评分".equals(tplName) && (score <= 10 || (score >= 11 && score <= 16) || (score >= 17 && score <= 21))) {
                    riskMap.put("highRiskName", "压");
                } else if ("Barthel评分".equals(tplName) && score <= 40) {
                    riskMap.put("highRiskName", "自");
                } else if ("营养风险筛查NRS2002评分".equals(tplName) && score >= 3) {
                    riskMap.put("highRiskName", "");
                } else if ("导管滑脱危险因素评分".equals(tplName) && score > 12) {
                    riskMap.put("highRiskName", "管");
                }else if (("Caprini评分".equals(tplName) && (score >= 5 || (score >= 3 && score <= 4))) || ("Padua评分".equals(tplName) && score >= 4) ) {
                    riskMap.put("highRiskName", "栓");
                } else {
                    riskMap.put("highRiskName", "");
                }
                if (StringUtils.isNotBlank(riskMap.get("highRiskName"))) {
                    riskList.add(riskMap);
                }
            }
        });
        if (riskList != null && riskList.size() > 0) {
            riskList.sort((a, b) -> (int) (DateUtil.stringToDate(a.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000) - (int) (DateUtil.stringToDate(b.get("fileDateModify"), "yyyy-MM-dd HH:mm:ss").getTime() / 1000));
        }
        patientMap.put("highRiskList", riskList);
        patientMap.putAll(conditions);
        if (StringUtils.isBlank(conditions.get("allergicDrugs"))) {
            patientMap.put("allergicDrugs", "无");//过敏药物信息
        }
        if (StringUtils.isBlank(conditions.get("disdaseState"))) {
            patientMap.put("disdaseState", "一般");//病情
        }
        if (StringUtils.isBlank(conditions.get("nursingGrade"))) {
            patientMap.put("nursingGrade", "无");//护理等级
        }
        if (StringUtils.isBlank(conditions.get("eatingHabits"))) {
            patientMap.put("eatingHabits", "无");//饮食习惯 (饮食过敏史)
        }
        if (StringUtils.isBlank(conditions.get("drugBacterialInfection"))) {
            patientMap.put("drugBacterialInfection", "0");//多重耐药菌感染信息
        }
        if (StringUtils.isBlank(conditions.get("responsibleNursePerson"))) {
            patientMap.put("responsibleNursePerson", "无");//责任护士
        }
        return patientMap;
    }

    public String toRepeatList(String data){
        List<String> list = new CopyOnWriteArrayList<>();
        if(StringUtils.isNotBlank(data)){
            for(String a1:data.split(",")){
                if(!list.contains(a1)){
                    list.add(a1);
                }
            }
            return StringUtils.join(list,",");

        }else{
            return "";
        }
    }

    @Override
    public Result getDepts() {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        List<Map<String, String>> deptList = transfusionMapper.getDepts(userId);
        return ResultGenerator.genOkResult(deptList);
    }

    @Override
    public Result getExamList(String inpatNum, String times, String type, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PatientExamListVO> examList = patientMapper.queryExamList(inpatNum, times, type);
        PageInfo pageInfo = new PageInfo<>(examList);
        return ResultGenerator.genOkResult(pageInfo);
    }

    @Override
    public Result getExamDetail(String examItemId) {
        PatientExamDetailVO examItemDetailVo = this.patientMapper.getExamItemDetail(examItemId);
        if (Objects.isNull(examItemDetailVo)) {
            throw new RuntimeException("检查不存在");
        }
        PatientExamDetailVO examDetailVO = this.patientMapper.getExamReportDetail(examItemDetailVo.getReqNum(), examItemDetailVo.getSerialNumber());
        if (Objects.isNull(examDetailVO)) {
            examDetailVO = new PatientExamDetailVO();
        }
        examDetailVO.setExamItemName(examItemDetailVo.getExamItemName());
        examDetailVO.setReqDoctor(examDetailVO.getReqDoctor());
        examDetailVO.setReqTime(examDetailVO.getReqTime());
        examDetailVO.setReqTime(examItemDetailVo.getReqTime());
        examDetailVO.setExamClass(examItemDetailVo.getExamClass());

        return ResultGenerator.genOkResult(examDetailVO);
    }


    @Override
    public Result getLabList(String inpatNum, String type, String times, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PatientLabListVO> labList = patientMapper.queryLabList(inpatNum, type, times);
        PageInfo pageInfo = new PageInfo<>(labList);
        return ResultGenerator.genOkResult(pageInfo);
    }

    @Override
    public Result geLabDetail(String labItemId) {
        // 获取检验详情
        PatientLabDetailVO vo = new PatientLabDetailVO();
        PatientLabTopDetailVO topDetailVO = this.patientMapper.getLabDetail(labItemId);
        // 获取检验报告详情
        vo.setLabReportDate(topDetailVO.getLabReportDate());
        vo.setSepcimenCategory(topDetailVO.getSepcimenCategory());
        List<PatientLabReportDetailVO> reportDetailVoList = this.patientMapper.getLabReportDetail(topDetailVO.getReqNum(), topDetailVO.getSerialNumber());
        if (!CollectionUtils.isEmpty(reportDetailVoList)) {
            vo.setReportDetailList(reportDetailVoList);
        }

        return ResultGenerator.genOkResult(vo);
    }

    @Override
    public Map<String, String> getPatientInfoWithComputeAge(String inpatNum) {
        if (StringUtils.isBlank(inpatNum)) {
            return new HashMap<>();
        }
        //根据入院号获取当前病人信息（姓名，入院号，年龄，床号，性别）
        Map<String, String> patientMap = transfusionMapper.queryPatientInfo(inpatNum);
        if (patientMap == null) {
            return null;
        }
        // 添加年龄
        patientMap.put("age", DateUtil.getAge(new AgeDTO(patientMap)));
        return patientMap;
    }

    @Override
    public List<Map<String, String>> listPatients(String wardId, String queryString) {
        return patientMapper.listPatients(wardId,queryString);
    }

    private void getPatientAge(Map<String, Object> patientInfo) {
        Integer ageYear = patientInfo.get("ageYear") == null ? 0 : Integer.parseInt(patientInfo.get("ageYear").toString());
        Integer ageMonth = patientInfo.get("ageMonth") == null ? 0 : Integer.parseInt(patientInfo.get("ageMonth").toString());
        Integer ageDay = patientInfo.get("ageDay") == null ? 0 : Integer.parseInt(patientInfo.get("ageDay").toString());
        Integer ageHour = patientInfo.get("ageHour") == null ? 0 : Integer.parseInt(patientInfo.get("ageHour").toString());
        Integer ageMinute = patientInfo.get("ageMinute") == null ? 0 : Integer.parseInt(patientInfo.get("ageMinute").toString());
        StringBuffer ageStr = new StringBuffer();
        if (ageYear != 0) {
            ageStr.append(ageYear + "岁");
        }
        if (ageMonth != 0) {
            ageStr.append(ageMonth + "月");
        }
        if (ageDay != 0) {
            ageStr.append(ageDay + "天");
        }
        if (ageHour != 0) {
            if (ageDay < 29) {              //28天以上不需要小时
                ageStr.append(ageHour + "小时");
            }
        }
        if (ageMinute != 0) {
            ageStr.append(ageMinute + "分钟");
        }
        if (ageStr.length() == 0) {
            ageStr.append(ageHour + "小时");
            ageStr.append(ageMinute + "分钟");
        }
        patientInfo.put("age", ageStr.toString());
    }

}
